package com.joy.joyusers.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joy.joyusers.common.BaseResponse;
import com.joy.joyusers.common.ErrorCode;
import com.joy.joyusers.common.ResultUtils;
import com.joy.joyusers.excption.BusinessException;
import com.joy.joyusers.model.VO.UserSearchVO;
import com.joy.joyusers.model.VO.UserVO;
import com.joy.joyusers.model.domain.User;
import com.joy.joyusers.model.request.UserLoginRequest;
import com.joy.joyusers.model.request.UserRegisterRequest;
import com.joy.joyusers.model.request.UserSearchRequest;
import com.joy.joyusers.service.UserService;
import com.joy.joyusers.utils.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.joy.joyusers.constant.HttpStatus.BAD_REQUEST;
import static com.joy.joyusers.constant.HttpStatus.BAD_REQUEST_MESSAGE;
import static com.joy.joyusers.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author jason
 */
@RestController
@RequestMapping("/user")
@CrossOrigin()
@Api("用户管理")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册请求体
     * @return 新用户id
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    public Response<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new IllegalArgumentException("请求体不能为空");
        }
        String account = userRegisterRequest.getAccount();
        String password = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(account, password, checkPassword)) {
            throw new IllegalArgumentException("账户或密码不能为空");
        }
        return userService.userRegister(account, password, checkPassword);
    }


    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求体
     * @return 用户信息
     */
    @PostMapping("/login")
    public BaseResponse<User> doLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String account = userLoginRequest.getAccount();
        String password = userLoginRequest.getPassword();
        System.out.println(account + " " + password);
        if (StringUtils.isAnyBlank(account, password)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.doLogin(account, password, request);
        if (user == null) {
            return ResultUtils.error(ErrorCode.ERROR_PASSWORDORGANIZATION, "用户名或密码错误");
        }
        return ResultUtils.success(user);
    }




    /**
     * 查询用户信息(用数据库缓存的例子)
     *
     * @param pageSize
     * @param request 用户查询请求体
     * @return 用户信息
     */
    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {

        // 如果缓存中存在数据，直接读取
        // 设计Redis的键值 systemid.modelid.func:options 不要和别人冲突 或者 partner.user:recommend:userid
        User user = userService.getCurrentLoginUser(request);                         // 获取当前用户登录id作为key
        String redisKey = String.format("partner:user:recommend:%s", user.getId());

        // 创建一个redistemplate操作对象 <String, Object>
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 从Redis中查询
        Page<User> userRedisdata = (Page<User>)valueOperations.get(redisKey);
        if (userRedisdata != null) {
            return ResultUtils.success(userRedisdata);     // 不为空则返回
        }
        // 为空则从数据库中查询，并写入缓存
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();            // 空条件
        // 改写成分页
        /**
         * 其中pageNum是当前页码（从1开始）
         * new Page<>((pageNum - 1) * pageSize, pageSize)
         * pageSize是每页显示的记录数
         * 比如计算第二页的起始索引，即pageNum是2
         * pageNum是2且pageSize是10，
         * 那么(pageNum - 1) * pageSize就是1 * 10 = 10，表示第二页的起始索引是10
         * 然后mybatis 分页已经mybatis plus自动做好了，所以这里传递页数就好，不用自己计算
         */
        Page<User> pageUserList = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        /**
         * 写入缓存，很重要，一定要设置过期时间！！！！！，这里设置为60毫秒吧
         * 不然redis内存无限增加就会触发redis的默认淘汰策略（什么按大小之类淘汰的），可能会把一些重要数据！！！！！！！
         */
        try {
            valueOperations.set(redisKey, pageUserList, 60000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.info("redis set key error",e);
        }
        return ResultUtils.success(pageUserList);
    }
    // 实测在后台查询100万条数据的情况下，响应时间从2秒 提升至 76毫秒


    /**
     * 查询用户信息
     *
     * @param userSearchRequest 用户查询请求体
     * @return 用户信息
     */
    @PostMapping("/search")
    @SaCheckLogin
    public Response<List<UserSearchVO>> searchUsers(@RequestBody UserSearchRequest userSearchRequest) {

        return userService.getQueryPage(userSearchRequest.getPageVO(), userSearchRequest.getUserSearchVO());
    }

    /**
     * 查询用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        // 查看缓存中是否存在用户信息
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        User userData = userService.getUserById(user.getId());
        User safeUser = userService.getSafetyUser(userData);
        return ResultUtils.success(safeUser);
    }

    /**
     * 删除用户
     *
     * @param userVO 用户信息
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Response<Boolean> deleteUser(@RequestBody UserVO userVO) {
        if (userVO.getId() < 0) {
            return new Response<>(BAD_REQUEST, BAD_REQUEST_MESSAGE, null);
        }
        return userService.deleteUser(userVO.getId());
    }

    /**
     * 用户登出
     *
     * @return 是否登出成功
     */
    @GetMapping("/logout")
    public BaseResponse<Integer> doLogout(HttpServletRequest request) {
        if(request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 邮箱验证码获取
     *
     * @param email 邮箱
     */
    @PostMapping("/email")
    public Response<Boolean> getEmailCode(@RequestParam("email") String email) {
        if (StringUtils.isBlank(email)) {
            return new Response<>(BAD_REQUEST, BAD_REQUEST_MESSAGE, null);
        }
        return userService.getEmailCode(email);
    }

    /**
     * 忘记密码
     *
     * @param email   邮箱
     * @param captcha 密码
     */
    @PostMapping("/forget")
    public Response<Boolean> forgetPassword(@RequestParam("email") String email,
                                            @RequestParam("captcha") String captcha,
                                            @RequestParam("password") String password,
                                            @RequestParam("account") String account) {
        if (StringUtils.isAnyBlank(email, captcha, password, account)) {
            return new Response<>(BAD_REQUEST, BAD_REQUEST_MESSAGE, null);
        }
        return userService.forgetPassword(email, captcha, password, account);
    }



    /**
     * 修改用户信息
     *
     * @param user 用户信息
     * @return 是否修改成功
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        // 1. 校验参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        System.out.println(user);
        // 2. 是否有权限修改
        User userInfo = userService.getCurrentLoginUser(request);        //获取一下用户信息

        int result = userService.modifyUser(user, userInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据tags搜索用户
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUserByTags(@RequestParam(required = false) List<String> tagNameList) {
        // 判空就行，具体的判断格式在service中编写就好
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数列表为空");
        }
        List<User> userList = userService.searchUserByTags(tagNameList);
        for(User userData: userList) {
            System.out.println(userData);
        }
        return ResultUtils.success(userList);
    }


}
